<template>
  <div>
    <h2>新闻资讯</h2>
    <el-button type="primary" @click="openAddDialog">添加</el-button>
    <el-dialog v-model="dialogVisible" title="新增新闻" width="500px">
      <el-form :model="form">
        <el-form-item label="标题">
          <el-input v-model="form.title" required></el-input>
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="form.content" type="textarea" required></el-input>
        </el-form-item>
        <el-form-item label="发布人">
          <el-input v-model="form.publisher" readonly></el-input>
        </el-form-item>
        <el-form-item label="发布时间">
          <el-date-picker v-model="form.publishTime" type="datetime" placeholder="选择发布时间" style="width: 100%" />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="form.noticeTypeId" placeholder="请选择类型">
            <el-option v-for="type in typeList" :key="type.id" :label="type.type" :value="type.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addNotice">确定</el-button>
      </template>
    </el-dialog>
    <el-divider></el-divider>
    <el-table :data="notices" style="width: 100%">
      <el-table-column prop="id" label="ID" width="60" />
      <el-table-column prop="title" label="标题" width="120" />
      <el-table-column prop="publisher" label="发布人" width="100" />
      <el-table-column label="类型" width="100">
        <template #default="scope">
          <span>{{ getTypeName(scope.row.noticeTypeId) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <span>{{ getStatusText(scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="publishTime" label="发布时间" width="160">
        <template #default="scope">
          <span>{{ formatDate(scope.row.publishTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160">
        <template #default="scope">
          <span>{{ formatDate(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="160">
        <template #default="scope">
          <span>{{ formatDate(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button type="primary" size="small" @click="showDetail(scope.row)">查看详情</el-button>
          <el-button v-if="scope.row.status === 0" type="warning" size="small" @click="aiAudit(scope.row)">AI审核</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="detailDialogVisible" title="新闻内容" width="500px" :before-close="() => detailDialogVisible = false">
      <div style="white-space: pre-wrap; font-size: 16px; padding: 16px;">
        {{ detailData.content }}
      </div>
      <div style="text-align: right; color: #888; font-size: 14px; padding: 0 16px 8px 0;">
        发布时间：{{ formatDate(detailData.publishTime) }}
      </div>
      <div style="text-align: right; color: #888; font-size: 14px; padding: 0 16px 16px 0;">
        状态：{{ getStatusText(detailData.status) }}
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from '../utils/request'

const notices = ref([])
const form = ref({ title: '', content: '', publisher: '', noticeTypeId: '', publishTime: '' })
const dialogVisible = ref(false)
const typeList = ref([])
const detailDialogVisible = ref(false)
const detailData = ref({})

const fetchNotices = async () => {
  const res = await axios.get('http://localhost:9999/notice-server/notice/all')
  // 先打印看下结构
  console.log(res.data)
  // 假如是 { code, msg, data } 结构
  notices.value = Array.isArray(res.data) ? res.data : res.data.data
}

const fetchTypes = async () => {
  const res = await axios.get('http://localhost:9999/notice-server/noticeType/all')
  typeList.value = Array.isArray(res.data) ? res.data : res.data.data
}

const addNotice = async () => {
  if (!form.value.title || !form.value.content) {
    ElMessage.error('标题和内容不能为空')
    return
  }
  
  const res = await axios.post('http://localhost:9999/notice-server/notice/add', form.value)
  if (res.data === true) {
    ElMessage.success('新增成功')
    form.value.title = ''
    form.value.content = ''
    form.value.publisher = ''
    form.value.noticeTypeId = ''
    form.value.publishTime = ''
    dialogVisible.value = false
    fetchNotices()
  } else {
    ElMessage.error('新增失败')
  }
}

function formatDate(val) {
  if (!val) return ''
  const d = new Date(val)
  // 只显示年月日
  return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0')
}

function getTypeName(id) {
  const type = typeList.value.find(t => t.id === id)
  return type ? type.type : id
}

function getStatusText(status) {
  switch (status) {
    case 0: return '待审核';
    case 1: return '已发布';
    case 2: return '已拒绝';
    default: return status;
  }
}

function showDetail(row) {
  detailData.value = { ...row }
  detailDialogVisible.value = true
}

async function aiAudit(row) {
  // 检查内容敏感词
  const contentCheckRes = await axios.post('sensitive-word/sensitive/check', { text: row.content })
  const contentCheckData = contentCheckRes.data || contentCheckRes.data.data

  // 检查标题敏感词
  const titleCheckRes = await axios.post('sensitive-word/sensitive/check', { text: row.title })
  const titleCheckData = titleCheckRes.data || titleCheckRes.data.data

  let sensitiveMsg = ''
  if (contentCheckData && (contentCheckData.contains === true || contentCheckData.contains === 'true')) {
    sensitiveMsg += '内容包含敏感词：' + (contentCheckData.sensitiveWords ? contentCheckData.sensitiveWords.join(',') : '') + '。'
  }
  if (titleCheckData && (titleCheckData.contains === true || titleCheckData.contains === 'true')) {
    sensitiveMsg += '标题包含敏感词：' + (titleCheckData.sensitiveWords ? titleCheckData.sensitiveWords.join(',') : '') + '。'
  }
  if (sensitiveMsg) {
    ElMessage.error(sensitiveMsg)
    return
  }

  // 审核通过，调用后端接口将状态改为1
  const updateRes = await axios.post('http://localhost:9999/notice-server/notice/updateStatus', { id: row.id, status: 1 })
  if (updateRes.data === true) {
    ElMessage.success('内容和标题未检测到敏感词，已自动发布！')
    fetchNotices()
  } else {
    ElMessage.error('状态更新失败')
  }
}

// 获取当前登录用户
function getCurrentUser() {
  const token = sessionStorage.getItem('token')
  if (!token) return ''
  try {
    const payload = token.split('.')[1]
    if (!payload) return ''
    const decodedStr = decodeURIComponent(escape(window.atob(payload)))
    const decoded = JSON.parse(decodedStr)
    // 取 user.username
    return decoded.user?.username || ''
  } catch (e) {
    console.error('解析token失败', e)
    return ''
  }
}

// 打开新增对话框时自动填充发布人
const openAddDialog = () => {
  form.value.title = ''
  form.value.content = ''
  form.value.noticeTypeId = ''
  form.value.publishTime = ''
  form.value.publisher = getCurrentUser()
  dialogVisible.value = true
}

onMounted(() => {
  fetchNotices()
  fetchTypes()
})
</script> 